# Copyright (c) 2018 Presto Labs Pte. Ltd.
# Author: leon

import csv
import os

from absl import flags, app

FLAGS = flags.FLAGS


def main(_):
  assert FLAGS.log_file_path
  assert FLAGS.output_dir
  exchange1 = FLAGS.exchange1
  exchange2 = FLAGS.exchange2
  assert exchange1
  assert exchange2
  csv_header = ['timestamp', 'last_feed_ms']

  csv1 = open(os.path.join(FLAGS.output_dir, 'last_feed_%s.csv' % exchange1), 'w', encoding='utf-8')
  writer1 = csv.writer(csv1, dialect='excel')
  writer1.writerow(csv_header)
  csv1.flush()

  csv2 = open(os.path.join(FLAGS.output_dir, 'last_feed_%s.csv' % exchange2), 'w', encoding='utf-8')
  writer2 = csv.writer(csv2, dialect='excel')
  writer2.writerow(csv_header)
  csv2.flush()

  with open(FLAGS.log_file_path) as infile:
    for line in infile:
      exploded = line.strip().split(' ')
      if len(exploded) < 10:
        continue
      timestamp = exploded[1]
      first_word = exploded[4]
      second_word = exploded[5]
      third_word = exploded[6]
      last_word = exploded[-1]
      last_second_word = exploded[-2]
      if last_word == 'ago' and last_second_word == 'ms':
        csv_line = [timestamp, exploded[-3]]
        if second_word == 'last':
          exchange_word = first_word
        elif third_word == 'last':
          exchange_word = '%s %s' % (first_word, second_word)
        else:
          raise ValueError(line)

        if exchange_word == exchange1:
          writer1.writerow(csv_line)
        elif exchange_word == exchange2:
          writer2.writerow(csv_line)
        else:
          raise ValueError(line)
    csv1.flush()
    csv2.flush()


if __name__ == "__main__":
  flags.DEFINE_string('log_file_path', None, 'Strategy log file path.')

  flags.DEFINE_string('output_dir', None, 'Output dir.')

  flags.DEFINE_string('exchange1', None, 'Feed exchange 1.')

  flags.DEFINE_string('exchange2', None, 'Feed exchange 2.')

  app.run(main)
